package org.web.controller;

import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.web.entity.User;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController()
@RequestMapping("/demo/*")
public class DemoController {
    private List<User> userList=new ArrayList<>();
    @GetMapping("hello")
    public String demo() {
        return "Hello, Web!";
    }
    @PostMapping("add")
    public Object add(@RequestBody User user){
        user.setId(UUID.randomUUID().toString());
        this.userList.add(user);
        return user;
    }
    @GetMapping("list")
    public Object list(){
        return this.userList.toArray();
    }
    @PutMapping("update")
    public Object update(@RequestBody User user){
        for (User u:userList) {
            if(u.getId().equals(user.getId())){
                if (!ObjectUtils.isEmpty(user.getName())){
                    u.setName(user.getName());
                }else if (!ObjectUtils.isEmpty(user.getAge())){
                    u.setAge(user.getAge());
                }
                return u;
            }
        }
        return null;
    }
    @DeleteMapping("delete")
    public Object delete(@RequestParam String id){
        for (int i = 0; i < userList.size(); i++) {
            if (userList.get(i).getId().equals(id)){
                userList.remove(i);
                return this.userList.toArray();
            }
        }
        return null;
    }
}
